import Taro from "@tarojs/taro"

export default {
  set(key: string, val: Taro.setStorage.Option["data"], async = true) {
    const data = JSON.stringify(val)
    try {
      if (async) {
        Taro.setStorageSync(key, data)
      } else {
        Taro.setStorage({
          key,
          data
        })
      }
    } catch (error) {
      console.log(`[ls.set] Error: key: ${key}, val: ${data}`)
    }
  },
  get<R = Taro.setStorage.Option["data"]>(key: string, defVal?: R): R {
    try {
      const val = Taro.getStorageSync(key)
      if (val) {
        return JSON.parse(val)
      }
    } catch (error) {
      console.log(`[ls.get] Error: key: ${key}`)
    }
    return defVal as R
  },
  del(key: string) {
    try {
      return Taro.removeStorageSync(key)
    } catch (error) {
      console.log(`[ls.del] Error: key: ${key}`)
    }
  },
  clear() {
    Taro.clearStorageSync()
  }
}
